package org.edu.modules.enroll.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.modules.enroll.entity.*;
import org.edu.modules.enroll.service.*;
import org.edu.modules.enroll.vo.VeZsPlanVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Api(tags="招生计划管理")
@RestController
@RequestMapping("enroll/planMng")
@Slf4j
public class VeZsPlanController extends BaseController<VeZsPlan, VeZsPlanService> {
    @Autowired
    private VeZsPlanService veZsPlanService;
    @Resource
    private VeDictQuarterService veDictQuarterService;
    @Resource
    private IVeBaseManageService iVeBaseManageService;

    @Resource
    private VeBaseSpecialtyService veBaseSpecialtyService;
    @Resource
    private VeBaseFacultyService veBaseFacultyService;
    //招生计划显示
    @AutoLog(value = "招生计划管理-显示表格")
    @ApiOperation(value="显示表格", notes="招生计划管理-显示表格")
    @PostMapping("/planMngShhow")
    //传到前端的参数路径 (pageNo-1)*pageSize就是pageNo
    public Result<?> planMngShhow(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "YXMC") String YXMC,
            @RequestParam(value = "ZYMC") String ZYMC
    ){
        List<Map<String,Object>> resList = new ArrayList<>();

        if (name.equals("")){
            //获取当前招生季
            QueryWrapper<VeDictQuarter> queryWrapper = new QueryWrapper<VeDictQuarter>().eq("isCur", 1);
            VeDictQuarter one = veDictQuarterService.getOne(queryWrapper);
            if(one==null){
                return Result.error("列表加载失败：未启用当前招生季");
            }
            name = one.getName();
        }
        Long falId = null;
        Long specialId = null;
        //获取所有专业
//        BasicResponseBO<List<VeBaseFaculty>> facultyBasicResponseBO = iVeBaseManageService.getFacultyAll();
//        List<VeBaseFaculty> facultyList = facultyBasicResponseBO.getResult();
        List<VeBaseFaculty> facultyList = veBaseFacultyService.list();//2021.9.2

            if (!YXMC.equals("") && ZYMC.equals("")){//专业无值
                for (VeBaseFaculty v : facultyList){
                    if (v.getYxmc().equals(YXMC)){
                        falId = v.getId();
                        break;
                    }
                }
            } else if (!YXMC.equals("") && !ZYMC.equals("")) {//院系，专业都有值
                for (VeBaseFaculty v : facultyList){
                    if (v.getYxmc().equals(YXMC)){
//                        BasicResponseBO<List<VeBaseSpecialty>> specialtyBasicResponseBO = iVeBaseManageService.getSpecialtyByFalId(v.getId());
//                        List<VeBaseSpecialty> specialtyList = specialtyBasicResponseBO.getResult();
                        QueryWrapper<VeBaseSpecialty> specialtyQueryWrapper = new QueryWrapper<>();
                        specialtyQueryWrapper.eq("falId",v.getId());
                        List<VeBaseSpecialty> specialtyList = veBaseSpecialtyService.list(specialtyQueryWrapper);//2021.9.2
                        for (VeBaseSpecialty specialty : specialtyList){
                            if (specialty.getZymc().equals(ZYMC)){
                                specialId = specialty.getId();
                            }
                        }
                    }

                }

            }

        if(veZsPlanService.lianbiao(name, falId, specialId).size()>0){

            List<VeZsPlanVo> planVoList = veZsPlanService.lianbiao(name, falId, specialId);

            for (VeZsPlanVo v : planVoList){//添加院系，专业名称
//                BasicResponseBO<VeBaseSpecialty> baseSpecialtyBasicResponseBO = iVeBaseManageService.getSpecialtyById(v.getSpecId());
                BasicResponseBO<VeBaseSpecialty> baseSpecialtyBasicResponseBO = new BasicResponseBO<>();
                baseSpecialtyBasicResponseBO.setResult(veBaseSpecialtyService.getById(v.getSpecId()));//2021.9.2
                if (baseSpecialtyBasicResponseBO.getResult()==null){
                    v.setZYMC("未查到专业名称");
                }else {
                    VeBaseSpecialty veBaseSpecialty = baseSpecialtyBasicResponseBO.getResult();
                    v.setZYMC(veBaseSpecialty.getZymc());
                }
//                BasicResponseBO<VeBaseFaculty> veBaseFacultyBasicResponseBO = iVeBaseManageService.getFacultyById(v.getFalId());
                BasicResponseBO<VeBaseFaculty> veBaseFacultyBasicResponseBO = new BasicResponseBO<>();
                veBaseFacultyBasicResponseBO.setResult(veBaseFacultyService.getById(v.getFalId()));//2021.9.2
                if (veBaseFacultyBasicResponseBO.getResult()==null){
                    v.setYXMC("未查到院系名称");
                }else {
                    VeBaseFaculty veBaseFaculty = veBaseFacultyBasicResponseBO.getResult();
                    v.setYXMC(veBaseFaculty.getYxmc());
                }
                Map<String,Object> res = new HashMap<>();
                res.put("plan",v);
                String url = veZsPlanService.findUrl(v.getFileId());
                if (url==null){
                    url += "/未上传附件";
                }
                res.put("url",url);
                resList.add(res);
            }


//        return Result.OK(planVoList);
            return Result.OK(resList);
}
        return Result.OK("招生计划显示失败");


    }

    @ApiOperation(value="批量删除")
    @PostMapping(value = "/deleteZs")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteZs(@ApiParam("拼接的ID字符串") @RequestParam(value = "ids") String ids){
//pius自带的批量删除
        boolean b = veZsPlanService.removeByIds(Arrays.asList(ids.split(",")));
        System.out.println(b);
        return Result.OK("删除成功！");

    }



    //删除
    @AutoLog(value = "招生计划管理-删除")
    @ApiOperation(value = "删除", notes = "招生计划管理-删除")
    @PostMapping("/sczsjh")
    //传到前端的参数路径
    public Result<?>  sczsjh(@RequestParam(value = "key") Integer id) {
        if (veZsPlanService.delQuarter( id) != 1) {
            return Result.OK("删除失败");
        }
        //发送请求到前端
        return Result.OK("删除成功");

    }


    //添加
    @AutoLog(value = "招生计划管理-添加")
    @ApiOperation(value = "添加", notes = "招生计划管理-添加")
    @PostMapping("/ZsjhAdd")
    //传到前端的参数路径
    public Result<?>  ZsjhAdd(

             @RequestParam(value ="falId")Integer falId,
            @RequestParam(value ="specId")Integer specId,
            @RequestParam(value ="ZSNF")String ZSNF,
            @RequestParam(value ="ZSJ")Integer ZSJ,
            @RequestParam(value ="BJS")Integer BJS,
            @RequestParam(value ="NANSRS")Integer NANSRS,
            @RequestParam(value ="NVSRS")Integer NVSRS,
            @RequestParam(value ="fileId")Integer fileId,
            @RequestParam(value ="ZYYQ")String ZYYQ,
            @RequestParam(value ="PYMB")String PYMB,
            @RequestParam(value ="ZYZYKC")String ZYZYKC,
            @RequestParam(value ="BXTJ")String BXTJ,
            @RequestParam(value ="remark")String remark,
            @RequestParam(value ="ZRS")Integer ZRS
//            @ApiParam("图片地址") @RequestParam(value = "fileUrl",required = false) String fileUrl,
//            @ApiParam("文件名") @RequestParam(value = "fileName",required = false) String fileName,
//             @ApiParam("尺寸") @RequestParam(value = "size",required = false) Long size
    ) {
        QueryWrapper<VeDictQuarter> wrapper = new QueryWrapper<>();
        wrapper.eq("id",ZSJ);
        VeDictQuarter quarter = veDictQuarterService.getOne(wrapper);
        if (!quarter.getYear().equals(ZSNF)){
            return Result.error("添加失败，招生年份与招生季年份不一致");
        }

//        VeFileFiles fileFiles = new VeFileFiles();
//        String[] arr = fileName.split("\\.");
//        String suffixName = arr[arr.length - 1];
//        fileFiles.setExt(suffixName);
//        fileFiles.setName(fileName);
//        fileFiles.setSourcefile(fileUrl);
//        fileFiles.setSize(size);
//        fileFiles.setCreatetime(System.currentTimeMillis() / 1000);
//        veZsPlanService.addFujian(fileFiles);
//        Integer fileId = veZsPlanService.findFileId(fileUrl);

        if (veZsPlanService.addZsjQuarter(falId, specId, ZSNF, ZSJ, BJS, NANSRS, NVSRS, fileId, ZYYQ, PYMB, ZYZYKC, BXTJ, remark, ZRS)==1) {
            return Result.OK("添加成功");
        }
        //发送请求到前端
        return Result.OK("添加失败");

    }

    //编辑
    @AutoLog(value = "招生计划管理-编辑")
    @ApiOperation(value = "编辑", notes = "招生计划管理-编辑")
    @PostMapping("/ZsjhSet")
    //传到前端的参数路径
    public Result<?>  ZsjhSet(

             @RequestParam(value ="falId")Integer falId,
            @RequestParam(value ="specId")Integer specId,
            @RequestParam(value ="ZSNF")String ZSNF,
            @RequestParam(value ="ZSJ")Integer ZSJ,
            @RequestParam(value ="BJS")Integer BJS,
            @RequestParam(value ="NANSRS")Integer NANSRS,
            @RequestParam(value ="NVSRS")Integer NVSRS,
            @RequestParam(value ="fileId",required=false)Integer fileId,
            @RequestParam(value ="ZYYQ")String ZYYQ,
            @RequestParam(value ="PYMB")String PYMB,
            @RequestParam(value ="ZYZYKC")String ZYZYKC,
            @RequestParam(value ="BXTJ")String BXTJ,
            @RequestParam(value ="remark")String remark,
            @RequestParam(value ="ZRS")Integer ZRS,
             @RequestParam(value = "key") Integer id
//             @ApiParam("图片地址") @RequestParam(value = "fileUrl",required = false) String fileUrl,
//             @ApiParam("文件名") @RequestParam(value = "fileName",required = false) String fileName,
//             @ApiParam("尺寸") @RequestParam(value = "size",required = false) Long size
    ) {
        QueryWrapper<VeDictQuarter> wrapper = new QueryWrapper<>();
        wrapper.eq("id",ZSJ);
        VeDictQuarter quarter = veDictQuarterService.getOne(wrapper);
        if (!quarter.getYear().equals(ZSNF)){
            return Result.error("编辑失败，招生年份与招生季年份不一致");
        }

//        VeFileFiles fileFiles = new VeFileFiles();
//        String[] arr = fileName.split("\\.");
//        String suffixName = arr[arr.length - 1];
//        fileFiles.setExt(suffixName);
//        fileFiles.setName(fileName);
//        fileFiles.setSourcefile(fileUrl);
//        fileFiles.setSize(size);
//        fileFiles.setCreatetime(System.currentTimeMillis() / 1000);
//        veZsPlanService.addFujian(fileFiles);
//        Integer fileId = veZsPlanService.findFileId(fileUrl);

        if (veZsPlanService.updateZsQuarter(falId, specId, ZSNF, ZSJ, BJS, NANSRS, NVSRS, fileId, ZYYQ, PYMB, ZYZYKC, BXTJ, remark, ZRS, id)==1) {
            return Result.OK("编辑成功");
        }
        //发送请求到前端
        return Result.OK("编辑失败");

    }

    //招生计划显示
    @AutoLog(value = "招生计划管理-编辑回显")
    @ApiOperation(value="编辑回显", notes="招生计划管理-编辑回显")
    @PostMapping("/jy")
    //传到前端的参数路径 (pageNo-1)*pageSize就是pageNo
    public Result<?> jy(
            @RequestParam(value = "key") Integer id
    ){

        if(veZsPlanService.ZsJy(id).size()>0){
            return Result.OK(veZsPlanService.ZsJy(id));
        }
        return Result.OK("招生计划显示失败");


    }

    //上传附件
    @AutoLog(value = "招生计划管理-上传附件")
    @PostMapping("/uploadFujian")
    public Result<?> uploadFujian(@ApiParam("文件") @RequestParam("file") MultipartFile file) throws Exception {
        File document = null;
        //获取文件名
        String fileName = file.getOriginalFilename();
        //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
        String[] arr = fileName.split("\\.");
        //获取文件后缀名
        String suffixName = arr[arr.length - 1];
        if (!suffixName.equalsIgnoreCase("jpg") && !suffixName.equalsIgnoreCase("png")) {
            return Result.error(400, "文件类型不能上传");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            document = File.createTempFile(filename[0], filename[1]);
            file.transferTo(document);
            document.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String docName = UUID.randomUUID().toString();
        //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
        OSSClient ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com","LTAI5tPnLGtPS6r8BpncZMrm","BAJbUlVLXD6or53Zcw1nC8uI87UpOs");
        PutObjectResult result = ossClient.putObject("exaplebucket-beijing",docName+"/"+ fileName, document);
        ossClient.shutdown();
        String fileUrl = "https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName;
        VeFileFiles fileFiles = new VeFileFiles();

//        String[] arr = fileName.split("\\.");
//        String suffixName = arr[arr.length - 1];
        fileFiles.setExt(suffixName);
        fileFiles.setName(fileName);
        fileFiles.setSourcefile(fileUrl);
        fileFiles.setSize(file.getSize());
        fileFiles.setCreatetime(System.currentTimeMillis() / 1000);
        veZsPlanService.addFujian(fileFiles);
        Integer fileId = veZsPlanService.findFileId(fileUrl);
//        return Result.OK("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);
        return Result.OK(fileId);
    }
}
